//
//  LBSViewController.m
//  LBSYunDemo
//
//  Created by RetVal on 3/23/13.
//  Copyright (c) 2013 RetVal. All rights reserved.
//

#import "LBSWebViewController.h"
#import "LBSIndex0ViewController.h"
#import "LBSDataBase.h"
#import "LBSTableViewCell.h"
#import "LBSRequestManager.h"
#import "LBSRental.h"
#import "LBSRequest+LBSSearchRegion.h"
#import "LBSRequest+LBSSearchNearby.h"
#import "LBSDataCenter.h"
#import "LBSSharedData.h"
#import "EGORefreshTableHeaderView.h"
#import "iToast.h"
#import <CoreLocation/CoreLocation.h>
#import "Constants.h"
typedef enum {
    EGOHeaderView = 0,
    EGOBottomView
} EGORefreshView;

@interface LBSIndex0ViewController () <	UITableViewDataSource,
                                        UITableViewDelegate,
                                        UISearchDisplayDelegate,
                                        UIPickerViewDataSource,
                                        UIPickerViewDelegate,
                                        UIScrollViewDelegate,
                                        EGORefreshTableHeaderDelegate,
                                        CLLocationManagerDelegate>
{
	NSMutableArray *_listContent;
	NSMutableArray *_filteredListContent;
	CLLocationManager *_manager;
	BOOL _tabBarHidden;
	BOOL _isLocationBasedSearch;
	
	NSUInteger _currentIndex;
	NSUInteger _pageSize;
	NSUInteger _totalItemCount;
	
	NSUInteger _pickerRegionIndex;
	NSUInteger _pickerRentalIndex;
	NSUInteger _pickerPriceIndex;
	NSUInteger _pickerLocationIndex;
}
@property (strong, nonatomic) EGORefreshTableHeaderView* refreshHeaderView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *searchBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *nearBtn;
@property (strong, nonatomic) UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (assign, nonatomic) BOOL tabBarHidden;	// for animate the TarBar

@property (strong, nonatomic) CLLocationManager *manager;
@property (strong, atomic) CLLocation *currentLocation;

@property (assign, atomic) BOOL loading;
@property (assign, atomic) BOOL noMoreResultsAvail;
@property (assign, atomic) BOOL isLocationBasedSearch;

@property (strong, atomic) NSMutableArray *listContent;
@property (strong, atomic) NSMutableArray *filteredListContent;

@property (strong, atomic) NSString *currentRegion;

@property (assign, atomic) NSUInteger pickerRegionIndex;
@property (assign, atomic) NSUInteger pickerRentalIndex;
@property (assign, atomic) NSUInteger pickerPriceIndex;
@property (assign, atomic) NSUInteger pickerLocationIndex;

@property (assign, atomic) BOOL userPickerChanged;
@end

@implementation LBSIndex0ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
	{
    }
    return self;
}

-(void)createHeaderView
{
    if (_refreshHeaderView && [_refreshHeaderView superview])
	{
        [_refreshHeaderView removeFromSuperview];
    }
	_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame: CGRectMake(0.0f, - self.tableView.bounds.size.height, self.tableView.frame.size.width, self.tableView.bounds.size.height)];
	
	_refreshHeaderView.delegate = self;
	_refreshHeaderView.tag = EGOHeaderView;
	[self.tableView addSubview:_refreshHeaderView];
	
    [_refreshHeaderView refreshLastUpdatedDate];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	NSLog(@"index 0 view did load");
	
    NSLog(@"%@", NSStringFromClass([[self tabBarController] class]));
    UITabBarController *tabbarController = (UITabBarController*)[self tabBarController];
    UITabBarItem *tabbarItem = [[tabbarController.tabBar items] objectAtIndex:0];
    tabbarItem.image = [UIImage imageNamed:@"UITabBarSearchTemplate.png"];
    
	_pageSize = 20;
	_currentIndex = 0;
	[[LBSSharedData sharedData] setCurrentIndex:_currentIndex];
    self.navigationController.navigationBar.translucent = NO;
	self.userPickerChanged = NO;
	
	self.listContent = [NSMutableArray array];
	_filteredListContent = [NSMutableArray arrayWithCapacity:10];
	
	// setup pickerView
	_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 445, 320, 216)];
	[self.view addSubview:_pickerView];
	_pickerView.showsSelectionIndicator = YES;
	_pickerView.frame = CGRectMake(0, 485, 320, 216);
	_pickerView.dataSource = self;
	_pickerView.delegate = self;
	
	// setup tableViewCell
	UINib* cellNib = [UINib nibWithNibName:@"LBSTableViewCell" bundle:nil];
	[self.tableView registerNib:cellNib forCellReuseIdentifier:LBSUIIndex0CellID];
	
	// setup tableView
	self.tableView.tableHeaderView = _searchBar;
	self.tableView.scrollEnabled = YES;
	
	// setup UI title
	self.navigationItem.title = NSLocalizedString(LBSUIIndex0Title, nil);
	_searchBtn.title = NSLocalizedString(LBSUIBarBtnPlace, nil);
	
	[self loadMoreData];
}

- (void)viewWillAppear:(BOOL)animated
{
	LBSSharedData *data = [LBSSharedData sharedData];
	self.pickerRegionIndex = data.regionIdx;
	self.pickerPriceIndex = data.priceRangeIdx;
	self.pickerRentalIndex = data.rentalTypeIdx;
	self.pickerLocationIndex = data.locationTypeIdx;
	_listContent = [[LBSSharedData sharedData] lastResult] ?: _listContent;
	[self.tableView reloadData];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[[LBSSharedData sharedData] setResult:_listContent];
}

- (void)viewDidAppear:(BOOL)animated
{
	// setup refreshView
	if (nil == self.refreshHeaderView) [self createHeaderView];
}

static void RSSetTabBarHidden(id context)
{
	LBSIndex0ViewController* self = context;
	for(UIView *view in self.tabBarController.view.subviews)
    {
		
		if([view isKindOfClass:[UITabBar class]])
        {
            if (self.tabBarHidden)
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y + view.frame.size.height,
										  view.frame.size.width,
										  view.frame.size.height)];
            }
			else
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y - view.frame.size.height,
										  view.frame.size.width,
										  view.frame.size.height)];
            }
        }
		else
        {
            if (self.tabBarHidden)
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y,
										  view.frame.size.width,
										  view.frame.size.height + (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) ? 49 : 0))];
            }
			else
			{
                [view setFrame:CGRectMake(view.frame.origin.x,
										  view.frame.origin.y,
										  view.frame.size.width,
										  view.frame.size.height - (([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) ? 49 : 0))];
            }
        }
    }
}

- (void)popUpPickerView:(UIBarButtonItem *)sender
{
	[self.pickerView reloadAllComponents];
    //self.pickerView.alpha=0.98;
    self.pickerView.backgroundColor = [UIColor whiteColor];
    
	if ([sender.title isEqualToString:LBSUIBarBtnPlace] ||
		[sender.title isEqualToString:LBSUIBarBtnNear])
	{
		_searchBtn.title = @"确定";
		self.tableView.scrollEnabled = NO;
		_searchBtn.enabled = NO;
		_nearBtn.enabled = NO;
		[UIView animateWithDuration:0.6 animations:^{
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			if ([[LBSDataCenter defaultCenter] isIphone5])
				self.pickerView.frame = CGRectMake(0, 288, 320, 216);
			else
				self.pickerView.frame = CGRectMake(0, 200, 320, 216);
			_tabBarHidden = YES;
			RSSetTabBarHidden(self);
		} completion:^(BOOL finished) {
			if (finished)
			{
				_searchBtn.enabled = YES;
				NSUInteger idx = [self.pickerView selectedRowInComponent:0];
				if (self.isLocationBasedSearch)
				{
					[self.pickerView selectRow:self.pickerLocationIndex inComponent:0 animated:YES];
				}
				else
				{
					if (idx == 0)
						[self.pickerView selectRow:self.pickerRegionIndex inComponent:1 animated:YES];
					else if (idx == 1)
						[self.pickerView selectRow:self.pickerPriceIndex inComponent:1 animated:YES];
					else if (idx == 2)
						[self.pickerView selectRow:self.pickerRentalIndex inComponent:1 animated:YES];
					else if (idx == 3)
						[self.pickerView selectRow:self.pickerLocationIndex inComponent:1 animated:YES];
				}
			}
		}];
	}
	else if ([sender.title isEqualToString:@"确定"])
	{
		_searchBtn.title = LBSUIBarBtnPlace;
		_searchBtn.enabled = NO;
		[UIView animateWithDuration:0.6 animations:^{
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			self.pickerView.frame = CGRectMake(0, 480, 320, 216);
			_tabBarHidden = NO;
			RSSetTabBarHidden(self);
		} completion:^(BOOL finished) {
			if (finished)
			{
				if (self.userPickerChanged)
				{
					[[LBSSharedData sharedData] setRegionIdx:self.pickerRegionIndex];
					[[LBSSharedData sharedData] setPriceRangeIdx:self.pickerPriceIndex];
					[[LBSSharedData sharedData] setRentalTypeIdx:self.pickerRentalIndex];
					[[LBSSharedData sharedData] setLocationTypeIdx:self.pickerLocationIndex];
					[self reloadData];
					self.userPickerChanged = NO;
				}
				
				_searchBtn.enabled = YES;
				_nearBtn.enabled = YES;
				self.tableView.scrollEnabled = YES;
			}
		}];
		if (_isLocationBasedSearch == NO)
		{
			
		}
		else
		{
			
		}
	}
}

- (IBAction)nearBtnPressed:(UIBarButtonItem *)sender
{
	_isLocationBasedSearch = YES;
	[self popUpPickerView:sender];	
}

- (IBAction)searchBtnPressed:(UIBarButtonItem *)sender
{
	if (![sender.title isEqualToString:@"确定"])
		_isLocationBasedSearch = NO;
	[self popUpPickerView:sender];
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
		return [_filteredListContent count];
	}
	
	NSInteger count = [self.listContent count];
	if (count) return count + 1;
	return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *reuseIdentifier = LBSUIIndex0CellID;
	static NSString *loadingMoreCellIdentifier = @"LoadingMoreCell";
	LBSTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
	if ([cell isLoading]) {
		cell = nil;
		[tableView.tableHeaderView setNeedsDisplay];
	}
	if (nil == cell)
	{
		UINib *cellNib = nil;
		[tableView registerNib:cellNib = [UINib nibWithNibName:@"LBSTableViewCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
		cell = [[cellNib instantiateWithOwner:self options:nil] lastObject];
	}
	if (tableView == [self.searchDisplayController searchResultsTableView])
	{
		LBSRental* rental = [_filteredListContent objectAtIndex:indexPath.row];
		if (rental.mainImage) cell.image = rental.mainImage;
		else if (rental.mainImageURL && cell.isLoading == NO)
		{
			cell.loading = YES;
			LBSRequest *request = [[LBSRequest alloc] initWithURL:rental.mainImageURL];
			request.userInfo = indexPath;
			[[LBSRequestManager defaultManager] addRequest:request dataComplete:^(LBSRequest *request, id dataModel) {
				if (dataModel)
				{
					dispatch_async(dispatch_get_main_queue(), ^{
						cell.image = [UIImage imageWithData:dataModel];
						cell.loading = NO;
						[cell setNeedsLayout];
					});
				}
			}];
		}
		cell.name = rental.rentalName;
		cell.price = [NSString stringWithFormat:@"可容纳%d", rental.price];
		cell.locationInformation = rental.locationName;
		cell.distanceInformation = [NSString stringWithFormat:@"距离:%4d米", rental.distance];
		cell.rentalTypeInformation = [NSString stringWithFormat:@"%@", rental.rentalType];
	}
	else
	{
		if (indexPath.row >= (self.listContent.count /5 *4))
		{
			if (NO == _loading && NO == _noMoreResultsAvail)
			{
				_loading = YES;
				// loadRequest is the method that loads the next batch of data.
				[self loadMoreData];
			}
		}
		if (self.listContent.count != 0)
		{
			// If the currently requested cell is not the last one, display normal data.
			// Else dispay @"Loading More..." or @"(No More Results Available)"
			if (indexPath.row < self.listContent.count)
			{
				LBSRental* rental = [self.listContent objectAtIndex:indexPath.row];
				cell.image = rental.mainImage;
				if (rental.mainImage) cell.image = rental.mainImage;
				else if (rental.mainImageURL && cell.isLoading == NO)
				{
					cell.loading = YES;
					LBSRequest *request = [[LBSRequest alloc] initWithURL:rental.mainImageURL];
					request.userInfo = indexPath;
					[[LBSRequestManager defaultManager] addRequest:request dataComplete:^(LBSRequest *request, id dataModel) {
						if (dataModel)
						{
							dispatch_async(dispatch_get_main_queue(), ^{
								cell.image = [UIImage imageWithData:dataModel];
								cell.loading = NO;
								[cell setNeedsLayout];
							});
						}
					}];
				}
				
				cell.name = rental.rentalName;
				cell.price = [NSString stringWithFormat:@"容纳%d人", rental.price];
				cell.locationInformation = rental.locationName;
				cell.distanceInformation = [NSString stringWithFormat:@"距离:%4d米", rental.distance];
				cell.rentalTypeInformation = [NSString stringWithFormat:@"%@", rental.rentalType];
				return cell;
			}
			else
			{
				// The currently requested cell is the last cell.
				if (!_noMoreResultsAvail)
				{
					// If there are results available, display @"Loading More..." in the last cell
					UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
																   reuseIdentifier:loadingMoreCellIdentifier];
					cell.textLabel.text = @"加载更多...";
					cell.textLabel.font = [UIFont systemFontOfSize:18];
					cell.textLabel.textColor = [UIColor colorWithRed:0.65f
															   green:0.65f
																blue:0.65f
															   alpha:1.00f];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
					cell.textLabel.textAlignment = NSTextAlignmentCenter;
#else
					cell.textLabel.textAlignment = UITextAlignmentCenter;
#endif
					return cell;
				}
				else
				{
					// If there are no results available, display @"Loading More..." in the last cell
					UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
																   reuseIdentifier:loadingMoreCellIdentifier];
					cell.textLabel.font = [UIFont systemFontOfSize:16];
					cell.textLabel.text = @"(无更多信息)";
					cell.textLabel.textColor = [UIColor colorWithRed:0.65f
															   green:0.65f
																blue:0.65f
															   alpha:1.00f];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
					cell.textLabel.textAlignment = NSTextAlignmentCenter;
#else
					cell.textLabel.textAlignment = UITextAlignmentCenter;
#endif
					return cell;
				}
			}
		}
		else
		{
			[self.tableView reloadData];
		}
	}
	return cell;
}

#pragma mark -
#pragma mark UI Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([segue.identifier isEqualToString:@"segueForWebView"] == YES)
    {
		LBSWebViewController *webViewController = segue.destinationViewController;
		LBSRental *rental = [_listContent objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
		webViewController.rental = rental;
    }
}

#pragma mark -
#pragma mark UITableViewDelegate
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (_tabBarHidden) return NO;
	return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	LBSRental* rental = nil;
	if (tableView ==  [self.searchDisplayController searchResultsTableView])
		rental = [_filteredListContent objectAtIndex:indexPath.row];
	else if (indexPath.row < _listContent.count)
	{
		rental = [_listContent objectAtIndex:indexPath.row];
	}
	if (rental && rental.roomURL)
	{
		[self performSegueWithIdentifier:@"segueForWebView" sender:self];
	}
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 88;
}

#pragma mark -
#pragma mark UISearchDisplayDelegate

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	[self.filteredListContent removeAllObjects];
	for (LBSRental *rental in self.listContent)
	{
		NSRange range = [rental.rentalName rangeOfString:searchText options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [rental.rentalName length])];
		if (range.location != NSNotFound)
		{
			[self.filteredListContent addObject:rental];
		}
	}
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
	[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
	return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
	[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
	return YES;
}

#pragma mark -
#pragma mark UIPickViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	if (self.isLocationBasedSearch) return 1;
	return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	if (component == 0)
	{
		if (self.isLocationBasedSearch)
		{
			return [[[LBSDataBase sharedInstance] nearbyRadius] count];
		}
		NSInteger cnt = 0;
		cnt = [[LBSDataBase sharedInstance] numberOfAllItems];
		if (cnt > 0) return cnt - 1;
		return cnt;
	}
	NSInteger idx = [pickerView selectedRowInComponent:0];
	if (idx != -1)
	{
		NSInteger cnt = 0;
		if (kLBSPlaceIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] placeNames] count];
		}
		else if (kLBSPriceIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] priceRanges] count];
		}
		else if (kLBSRentalIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] rentalTypes] count];
		}
		else if (kLBSNearbyIndex == idx)
		{
			cnt = [[[LBSDataBase sharedInstance] nearbyRadius] count];
		}
		return cnt;
	}
	return 0;
}

#pragma mark -
#pragma mark UIPickViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	self.userPickerChanged = YES;
	if (0 == component)
	{
		NSInteger idx = [pickerView selectedRowInComponent:component];
		if (-1 == idx) return;
		if (idx != -1 && !self.isLocationBasedSearch)
		{
			[_pickerView reloadComponent:1];
		}
		if (self.isLocationBasedSearch)
		{
			self.pickerLocationIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			return;
		}
		if (idx == 0)
			[self.pickerView selectRow:self.pickerRegionIndex inComponent:1 animated:YES];
		else if (idx == 1)
			[self.pickerView selectRow:self.pickerPriceIndex inComponent:1 animated:YES];
		else if (idx == 2)
			[self.pickerView selectRow:self.pickerRentalIndex inComponent:1 animated:YES];
	}
	else
	{
		NSInteger idx = [pickerView selectedRowInComponent:0];
		if (idx != -1)
		{
			if (kLBSPlaceIndex == idx)
			{
				self.pickerRegionIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSPriceIndex == idx)
			{
				self.pickerPriceIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSRentalIndex == idx)
			{
				self.pickerRentalIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
			else if (kLBSNearbyIndex == idx)
			{
				self.pickerLocationIndex = row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1);
			}
		}
		
	}
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    
	UILabel *myView = nil;
	if (component == 0)
	{
		if (self.isLocationBasedSearch)
		{
			myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 280, 30)];
			myView.text = [[[LBSDataBase sharedInstance] nearbyRadius] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
		}
		else
		{
			myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
			myView.text = [[[LBSDataBase sharedInstance] itemsNames] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
		}
		
		// UITextAlignmnetCenter被iOS 6作为废弃定义了
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
		myView.textAlignment = NSTextAlignmentCenter;
#else
		myView.textAlignment = UITextAlignmentCenter;
#endif
		
		myView.font = [UIFont systemFontOfSize:14];     
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE_7_0
//		myView.backgroundColor = [UIColor clearColor];
//#else
        myView.backgroundColor = [UIColor clearColor];
//#endif
	}
	else
	{
		myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 180, 30)];
		// UITextAlignmentCenter被iOS 6作为废弃定义了
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
		myView.textAlignment = NSTextAlignmentCenter;
#else
		myView.textAlignment = UITextAlignmentCenter;
#endif
		NSInteger idx = [pickerView selectedRowInComponent:0];
		if (idx != -1)
		{
			//NSInteger cnt = 0;
			if (kLBSPlaceIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] placeNames] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
			else if (kLBSPriceIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] priceRanges] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
			else if (kLBSRentalIndex == idx)
			{
				myView.text = [[[LBSDataBase sharedInstance] rentalTypes] objectAtIndex:row % ([self pickerView:pickerView numberOfRowsInComponent:component] ? : 1)];
			}
		}
		myView.font = [UIFont systemFontOfSize:14];
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE_7_0
//		myView.backgroundColor = [UIColor whiteColor];
//#else
        myView.backgroundColor = [UIColor clearColor];
//#endif
	}
	
	return myView;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	CGFloat componentWidth = 0.0;
	if (self.isLocationBasedSearch)
	{
		return 280;
	}
	if (component == 0)
		componentWidth = 100.0; // 第一个组键的宽度
	else
		componentWidth = 180.0; // 第2个组键的宽度
	return componentWidth;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 60;
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate

- (void)stopLoading
{
	[self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
	[self.refreshHeaderView refreshLastUpdatedDate];
	_loading = NO;
}

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
	_loading = YES;
	[self reloadData];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	return _loading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	return [[NSDate alloc] init];
}
#pragma mark -
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	if (self.searchDisplayController.searchResultsTableView != scrollView)
		[self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	if (self.searchDisplayController.searchResultsTableView != scrollView)
		[self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark Data Model

- (void)loadDataWithLocation:(CLLocationCoordinate2D)location radius:(NSUInteger)radius
{
	[[LBSDataCenter defaultCenter] loadDataWithNearby:location radius:radius index:_currentIndex pageSize:_pageSize pieceComplete:^(LBSRequest *request, NSDictionary *dataModel) {
		if (dataModel)
		{
            LBSRental *rental = [[LBSRental alloc] initWithDataModel:dataModel];
            if (rental)
            {
                [self.listContent addObject:rental];
            }
		}
		else
		{
			dispatch_async(dispatch_get_main_queue(), ^{
				NSLog(@"reload data now.");
				_totalItemCount = request.availableItemCount;
				NSLog(@"total:%d, loaded:%d", _totalItemCount, [self.listContent count]);
				NSUInteger curCnt = [self.listContent count];
				if (curCnt >= _totalItemCount)
					_noMoreResultsAvail = YES;
				if (request.error)
					[iToast make:LBSUINetWorkError duration:750];
				else if (request.availableItemCount)
					[iToast make:LBSUIDataComplete duration:750];
				else
					[iToast make:LBSUINoMoreData duration:750];
				[self.tableView reloadData];
				[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
			});
		}
	}];
}

- (void)logInformation
{
	NSLog(@"%@, %@, %@",
		  [[[LBSDataBase sharedInstance] placeNames] objectAtIndex:self.pickerRegionIndex],
		  [[[LBSDataBase sharedInstance] priceRanges] objectAtIndex:self.pickerPriceIndex],
		  [[[LBSDataBase sharedInstance] rentalTypes] objectAtIndex: self.pickerRentalIndex]);
}

- (void)loadMoreData
{
	[self logInformation];
	[iToast make:@"加载中..." duration:1000000];
	if (self.isLocationBasedSearch)
	{
		NSUInteger radius = 100000000;
		
        NSString *locationTag = nil;
		locationTag = [[[LBSDataBase sharedInstance] nearbyRadius] objectAtIndex:self.pickerLocationIndex];
		if ([locationTag isEqualToString:@"附近1000米"])
			radius = 1000;
		else if ([locationTag isEqualToString:@"附近3000米"])
			radius = 3000;
		else if ([locationTag isEqualToString:@"附近5000米"])
		    radius = 5000;
        else if ([locationTag isEqualToString:@"附近5000米"])
		    radius = 5000;
        else if ([locationTag isEqualToString:@"10公里以内"])
		    radius = 10000;
        else if ([locationTag isEqualToString:@"30公里以内"])
		    radius = 30000;
        else if ([locationTag isEqualToString:@"50公里以内"])
		    radius = 50000;
        else if ([locationTag isEqualToString:@"100公里以内"])
		    radius = 100000;
        else
		    radius = 100000000;
		
		[[LBSRequestManager defaultManager] addRequest:[[LBSRequest alloc] initWithURL:[NSURL URLWithString:kLBSRequestUpdateLocation]] locationUpdateComplete:^(CLLocation *location) {
			if (location)
			{
				[[LBSSharedData sharedData] setCurrentCoordinate2D:location.coordinate];
				[self loadDataWithLocation:location.coordinate radius:radius];
			}
			else
			{
				[iToast make:@"定位失败:(" duration:750];
				dispatch_async(dispatch_get_main_queue(), ^{
					NSLog(@"reload data now.");
					[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
				});
			}
		}];
		return;
	}
	NSRange priceRange = {0,0};
	if (self.pickerPriceIndex)
	{
		NSArray * names = [[LBSDataBase sharedInstance] priceRanges];
		NSString * priceTag = nil;
		priceTag = [names objectAtIndex:self.pickerPriceIndex];
		if ([priceTag isEqualToString:@"5千人以下"])
			priceRange = NSMakeRange(0, 5000);
		else if ([priceTag isEqualToString:@"5千-1万人"])
			priceRange = NSMakeRange(5000, 10000);
		else if ([priceTag isEqualToString:@"1万-2万人"])
			priceRange = NSMakeRange(10000, 20000);
		else if ([priceTag isEqualToString:@"2万-5万人"])
			priceRange = NSMakeRange(20000, 50000);
		else if ([priceTag isEqualToString:@"5万-10万人"])
			priceRange = NSMakeRange(50000, 100000);
		else if ([priceTag isEqualToString:@"10万-20万人"])
			priceRange = NSMakeRange(100000, 200000);
		else if ([priceTag isEqualToString:@"20万人以上"])
			priceRange = NSMakeRange(200000, 99999999);
	}
	[[LBSDataCenter defaultCenter] loadDataWithRegionName:[[[LBSDataBase sharedInstance] placeNames] objectAtIndex:self.pickerRegionIndex] priceRange:priceRange rentalType:self.pickerRentalIndex index:_currentIndex pageSize:_pageSize pieceComplete:^(LBSRequest *request, id dataModel) {
		if (dataModel)
		{
            LBSRental *rental = [[LBSRental alloc] initWithDataModel:dataModel];
            if (rental)
            {
                [self.listContent addObject:rental];
            }
		}
		else
		{
			dispatch_async(dispatch_get_main_queue(), ^{
				NSLog(@"reload data now.");
				_totalItemCount = request.availableItemCount;
				NSLog(@"total:%d, loaded:%d", _totalItemCount, [self.listContent count]);
				NSUInteger curCnt = [self.listContent count];
				if (curCnt >= _totalItemCount)
					_noMoreResultsAvail = YES;
				_loading = NO;
				if (request.error)
					[iToast make:LBSUINetWorkError duration:750];
				else if (request.availableItemCount)
					[iToast make:LBSUIDataComplete duration:750];
				else
					[iToast make:LBSUINoMoreData duration:750];
				[self.tableView reloadData];
				[self performSelector:@selector(stopLoading) withObject:nil afterDelay:0.5];
			});
		}
	}];
	_currentIndex++;
	[[LBSSharedData sharedData] setCurrentIndex:_currentIndex];
}

- (void)reloadData
{
	_currentIndex = 0;
	[[LBSSharedData sharedData] setCurrentIndex:_currentIndex];
	_noMoreResultsAvail = NO;
	[self.listContent removeAllObjects];
	[self loadMoreData];
}
- (void)viewDidUnload {
	[self setNearBtn:nil];
	[super viewDidUnload];
}
@end
